import React, { useContext, useEffect } from 'react';
import { message } from 'antd';
import { useRequest } from '@/hooks';
import { isEmpty } from 'lodash';
import { connect } from 'umi';

import { isSuccess } from '@/utils/request';
import pageTabUtil from '@/utils/pageTabUtil';

import { getOrganizationList } from '@/services/Organization/orgmanage';
import { getCurrentCompanyCode } from '@/pages/SalaryManage/utils';
import { convertTreeToArray } from '@/pages/SalaryManage/utils/treeUtil';
import modelType from '@/pages/SalaryManage/constant/commonModelType';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';

/**
 * @param enableDefaultSelect 当没有选择行政机构时，是否启用自动选择功能
 * @param selectOrganizationCode 选择的行政机构
 * @param countryNameCode 选择行政机构的国别
 * @param children
 * @param dispatch
 * @param namespace 对应model的namespace, 由于多页签的原因，namespace这种方式尽量不要使用
 * @returns {JSX.Element}
 * @constructor
 */
const OrganizationFilter = ({
    enableDefaultSelect,
    selectOrganizationCode,
    countryNameCode,
    children,
    dispatch,
    namespace
}) => {
    const { mergeTabStore } = useContext(TabStoreContext);
    const { data: orgResponse, run: fetchOrganizationList } = useRequest(
        () =>
            getOrganizationList({
                organizationPermissions: 1,
                showTreeFlag: 1
            }),
        { manual: true }
    );

    useEffect(() => {
        fetchOrganizationList();
    }, [fetchOrganizationList]);

    useEffect(() => {
        if (!orgResponse) {
            return;
        }

        if (!isSuccess(orgResponse)) {
            message.error(orgResponse.msg);
            return;
        }

        const orgTreeArray = orgResponse.data;

        if (orgTreeArray?.length > 0) {
            const orgList = convertTreeToArray(
                orgTreeArray,
                'children',
                org => org.organizationType === 1 || org.organizationType === 2
            );
            const companyCode = getCurrentCompanyCode();

            if (!orgList?.length) {
                message.warn('没有可用的菜单！');
                pageTabUtil.closeTab();
                return;
            }

            const currentCompanyOrg = orgList.find(org => org.organizationCode === companyCode);
            const defaultSelectOrg = currentCompanyOrg || orgList?.[0];
            const defaultPayload = {
                organizationResponse: orgResponse,
                organizationList: orgList
            };

            const payload = {};

            // 设置默认行政机构
            if (!selectOrganizationCode && defaultSelectOrg) {
                payload.defaultOrganization = defaultSelectOrg;
            }

            // 如果启用选择默认行政机构， 设置默认行政机构
            if (enableDefaultSelect && defaultSelectOrg && !selectOrganizationCode) {
                payload.selectOrganizationCode = defaultSelectOrg.organizationCode;
                payload.countryNameCode = defaultSelectOrg.countryNameCode;
            }

            if (selectOrganizationCode && !countryNameCode) {
                payload.countryNameCode = orgList.find(
                    org => org.organizationCode === selectOrganizationCode
                )?.countryNameCode;
            }

            if (!isEmpty(payload)) {
                if (namespace) {
                    dispatch({
                        type: `${namespace}/${modelType.SET_MULTI_STORE}`,
                        payload: Object.assign(defaultPayload, payload)
                    });
                } else {
                    mergeTabStore(Object.assign(defaultPayload, payload));
                }
            }
        }
    }, [orgResponse, selectOrganizationCode, countryNameCode, namespace, dispatch, enableDefaultSelect, mergeTabStore]);

    return <>{children}</>;
};
OrganizationFilter.defaultProps = {
    enableDefaultSelect: true
};

const MenuFilterConn = namespace =>
    connect(({ [namespace]: model }) => ({
        selectOrganizationCode: model.selectOrganizationCode,
        namespace
    }))(OrganizationFilter);

const TabContextMenuFilter = ({ children, ...otherProps }) => {
    const {
        store: { selectOrganizationCode, countryNameCode }
    } = useContext(TabStoreContext);
    return (
        <OrganizationFilter
            {...otherProps}
            selectOrganizationCode={selectOrganizationCode}
            countryNameCode={countryNameCode}
        >
            {children}
        </OrganizationFilter>
    );
};

export { MenuFilterConn as MenuFilter, TabContextMenuFilter };
